# coding = utf-8
# File date: Hi_2022/11/15 23:08
# File_name: tool_method.py
import time
import os
from tkinter import Label, scrolledtext, END, messagebox
from tkinter.filedialog import askopenfilename
from tkinter.scrolledtext import ScrolledText
from GUI_log import log_out

# 日志初始化
g_log = log_out()


def write_to_text(open_label: Label, texts: scrolledtext):
    """
    :param open_label: 读取的文件路径
    :param texts: 已经实例化的滚动文板框
    :return: 把读取的信息写入滚动文板框,无返回
    """
    file_path = askopenfilename(
        title="请选择要打开的文件！",
        defaultextension="txt",
        initialdir=os.path.join(os.getcwd(), "record"),
        filetypes=[("文本文档", "*.txt")])

    # 更新label信息
    if not file_path:  # 直接关闭的话
        g_log.warning("未打开录像文件, 停止写入")
        return

    g_log.info(f"选择录像文件:{file_path}")

    open_label["text"] = file_path
    g_log.success("播放界面label已更新")

    # 删除提前输入的东西
    texts.delete("0.0", END)
    g_log.success("删除播放界面滚动文本框所有信息成功")

    with open(file_path, encoding="utf-8", mode="r+") as open_file:
        for line_str in open_file.readlines():  # 逐行把读取到的信息插入多行文本框
            texts.insert(END, line_str)
            line_str = line_str.replace("\n", "")
            g_log.info(f"向滚动文本框插入：{line_str}")


def write_to_txt(open_label: Label, text: ScrolledText):
    """
    :param open_label: 当前label对象
    :param text: scrolledtext文本框对象
    :return: 把text读取到的内容写入txt,保存读取的信息并提示
    """
    path = open_label["text"]
    if not path:
        messagebox.showwarning("未打开文件", "请先打开需要播放的录像文件,并修改后再次保存")
        g_log.warning("请先打开需要播放的录像文件,并修改后再次保存")
        return

    text_message = text.get("0.0", END)
    with open(path, encoding="utf-8", mode="w") as open_file:
        open_file.write(text_message)

    g_log.success(f"滚动文本框信息写入{path}完成")

    # 弹窗提示
    messagebox.showinfo(title='保存成功！', message=f'已保存至\n{path}')  # 提示信息对话窗


def creat_record_file(open_label: Label):
    """
    :param open_label: 需要更新的label
    :return:无返回创建录像文件,并更新label
    """
    # 获取当前格式化时间,并处理成%Y_%m_%d_%H_%M_%S.%ms格式时间字符串
    current_timestamp = time.time()
    format_time = time.localtime(current_timestamp)
    file_name = f"{time.strftime('%Y%m%d%H%M%S%m', format_time)}.txt"
    path = os.path.join(os.path.abspath("./record"), file_name)
    open(path, mode="w", encoding="utf-8").close()  # 创建文件
    open_label["text"] = path  # 更新label的值
    g_log.success(f"创建录像文件成功：{path}")


def get_time():
    """把时间戳精确到小数点后6位的浮点数,并返回"""
    time_now = time.time()
    time_now = round(time_now, 6)
    g_log.info(f"获取当前时间并保留6位数小数结果：{time_now}")
    return time_now


def get_sleep_time(last_time: float):
    """相减的精度时间返回"""
    g_log.info(f"get_sleep_time读取上一次操作时间：{last_time}")
    sleep_time = get_time() - last_time
    sleep_time = round(sleep_time, 6)
    g_log.info(f"获取当前时间和上一次差并保留6位数小数结果：{sleep_time}")
    return sleep_time
